package com.web.position.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.sun.deploy.net.URLEncoder;
import com.web.common.BaseResult;
import com.web.common.ReturnCode;
import com.web.common.enums.BaseStatus;
import com.web.config.ExcelStylerUtil;
import com.web.position.entity.Position;
import com.web.position.service.PositionService;
import com.web.transaction.entity.Transaction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Api(value = "API - PositionController",description = "position")
@RestController
@CrossOrigin
@RequestMapping("/position")
public class PositionController {

    @Autowired
    private PositionService positionService;

    @RequestMapping(value = "/addPosition",method = RequestMethod.POST)
    @ApiOperation(value = "新增position")
    public BaseResult addPosition(@RequestBody Position position){
        positionService.addPosition(position);
        return new BaseResult(BaseStatus.SUCCESS.getCode(),BaseStatus.FCE_INSERT_SUCCESS.getDesc());
    }

    @RequestMapping(value = "/positionList")
    public BaseResult<List<Position>> positionList(@ModelAttribute Position t){
    	List<Position> positionList = positionService.getPositions(t);
    	return new BaseResult<>(BaseStatus.SUCCESS.getCode(),positionList);
    }


    @RequestMapping(value = "/positionEchartsList")
    public BaseResult positionEchartsList(){
        List<Map<String,String>> echartsData = positionService.getPositonForIndex();
        return new BaseResult<>(BaseStatus.SUCCESS.getCode(),echartsData);
    }

    @RequestMapping(value = "/export")
    public void exportPosition(@ModelAttribute Position position, HttpServletResponse response) throws IOException {
        List<Position> positionList = positionService.getPositions(position);

        String fileName = "拆盘交易数据";
        String sheetName = "Position交易数据";
        ExportParams exportParams = new ExportParams(fileName,sheetName, ExcelType.XSSF);
        exportParams.setStyle(ExcelStylerUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Position.class, positionList);

        //将表格输出
        fileName = URLEncoder.encode(fileName,"UTF8");
        //设置返回数据类型
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        workbook.write(response.getOutputStream());
    }

}
